package zhihui.mobile.presenter.shop;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zhihui.mobile.R;
import zhihui.mobile.bean.page.PageInfo;
import zhihui.mobile.bean.shop.BannerInfo;
import zhihui.mobile.bean.shop.CategoryShopInfo;
import zhihui.mobile.bean.shop.SkuInfo;
import zhihui.mobile.bean.shop.SpuInfo;
import zhihui.mobile.bean.shop.cart.CartInfo;
import zhihui.mobile.bean.shop.category.CategoryInfo;
import zhihui.mobile.bean.shop.sales.SalesInfo;
import zhihui.mobile.bean.shop.sales.SalesListData;
import zhihui.mobile.config.Config;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.shop.CategoryManager;
import zhihui.mobile.manager.shop.ShopManager;
import zhihui.mobile.manager.shop.ShopSalesManager;
import zhihui.mobile.manager.token.TokenManager;
import zhihui.mobile.manager.user.UserManager;
import zhihui.mobile.net.HttpUtils;
import zhihui.mobile.ui.IView;
import zhihui.mobile.ui.shop.IShopMainContract;
import zhihui.mobile.ui.shop.IShopMainContract.IShopMainPresenter;
import zhihui.mobile.ui.shop.ShopMainActivity;
import zhihui.mobile.ui.shop.category.ShopCategoryActivity;
import zhihui.mobile.ui.shop.sales.ShopSalesActivity;

/**
 * Created by 张公铭 on 2017/7/21 0021.
 */

public class ShopMainPresenter extends BaseShopPresenter implements IShopMainPresenter
{
    private Logger logger = Logger.getLogger(ShopMainPresenter.class);
    private Context mContext;
    private IShopMainContract.IShopMainView shopMainView;
    private int count = 3;

    @Override
    public void init(IView view, Context context)
    {
        mContext = context;
        shopMainView = (IShopMainContract.IShopMainView) view;
    }

    @Override
    public void onResume()
    {
        shopMainView.searchRequestFocus();
        shopMainView.updateCartNum(ShopManager.getInstance().getCartInfo().getCartNum());
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onPause()
    {

    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onDestroy()
    {

    }

    @Override
    public void initView()
    {
        new InitDataTask().execute();
    }

    class InitDataTask extends AsyncTask<Void, Void, Boolean>
    {
        @Override
        protected void onPreExecute()
        {
            shopMainView.showLoading();
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {

            if (!TokenManager.getInstance().checkToken())
            {
                boolean result = TokenManager.getInstance().getToken();
                if (!result)
                {
                    return false;
                }
            }

            final ShopManager manager = ShopManager.getInstance();
            manager.initShopMain(new IHttpCallBackListener()
            {
                @Override
                public void success(JSONObject result)
                {
                    try
                    {
                        JSONArray ary = result.getJSONArray("data");
                        Gson gson = new Gson();
                        List<BannerInfo> list = gson.fromJson(ary.toString(), new TypeToken<List<BannerInfo>>()
                        {
                        }.getType());
                        manager.getShopMainBanner().clear();
                        manager.getShopMainGroup().clear();
                        manager.getShopMainTopic().clear();
                        for (BannerInfo bannerInfo : list)
                        {
                            switch (bannerInfo.getType())
                            {
                                case 1:
                                    manager.getShopMainBanner().add(bannerInfo);
                                    break;
                                case 2:
                                    manager.getShopMainGroup().add(bannerInfo);
                                    break;
                                case 3:
                                    manager.getShopMainTopic().add(bannerInfo);
                                    break;
                            }
                        }
                    } catch (JSONException e)
                    {
                        logger.error("解析错误：" + e.getMessage());
                        shopMainView.showMessage(mContext.getString(R.string.json_error));
                    }
                    --count;
                }

                @Override
                public void failed(String message)
                {
                }
            });

            manager.initShopMianRecommend(new IHttpCallBackListener()
            {
                @Override
                public void success(JSONObject result)
                {
                    Gson gson = new Gson();
                    try
                    {
                        JSONObject data = result.getJSONObject("data");
                        PageInfo pageInfo = gson.fromJson(data.toString(), PageInfo.class);
                        manager.setCurPageInfo(pageInfo);

                        List<SpuInfo> list = gson.fromJson(data.getJSONArray("list").toString(), new TypeToken<List<SpuInfo>>()
                        {
                        }.getType());
                        manager.getRecommendList().clear();
                        manager.setRecommendList(list);

                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                    --count;
                }

                @Override
                public void failed(String message)
                {
                }
            }, 1, 10);

            manager.initShopMainSales(new IHttpCallBackListener()
            {
                @Override
                public void success(JSONObject result)
                {
                    JSONObject data = null;
                    Gson gson = new Gson();
                    try
                    {
                        data = result.getJSONObject("data");
                        JSONObject qgJson = data.getJSONObject("zk");
                        SalesInfo qgSales = gson.fromJson(qgJson.toString(), SalesInfo.class);
                        manager.setQgSales(qgSales);
                    }catch (JSONException e)
                    {
                        manager.setQgSales(null);
                    }

                    try{
                        JSONObject msJson = data.getJSONObject("ms");
                        SalesInfo msSales = gson.fromJson(msJson.toString(), SalesInfo.class);
                        manager.setMsSales(msSales);

                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                        manager.setMsSales(null);
                    }
                    --count;
                }

                @Override
                public void failed(String message)
                {

                }
            });

            if (UserManager.getInstance().getCurUser() != null)
            {
                count++;
                manager.getCartShopList(new IHttpCallBackListener()
                {
                    @Override
                    public void success(JSONObject result)
                    {
                        try
                        {
                            JSONObject data = result.getJSONObject("data");
                            CartInfo cartInfo = new CartInfo();
                            cartInfo.setCartNum(data.getInt("cartNum"));
                            Gson gson = new Gson();
                            List<SkuInfo> list = gson.fromJson(data.getJSONArray("skus").toString(), new TypeToken<List<SkuInfo>>()
                            {
                            }.getType());
                            cartInfo.setSkus(list);
                            ShopManager.getInstance().setCartInfo(cartInfo);
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                        --count;
                    }

                    @Override
                    public void failed(String message)
                    {

                    }
                });
            }

            int time = 1;
            while (count > 0 && time < 15)
            {
                try
                {
                    Thread.sleep(1000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                time++;
                Log.i("xxxx", "while........................................." + count);
            }
            if (count > 0)
            {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean)
        {

            Log.i("xxxx", "我回来了..........");

            if (!aBoolean)
            {
                shopMainView.showMessage("网络超时,请重新尝试...");
                shopMainView.goBack(ShopMainActivity.class);
                return;
            }
            shopMainView.updateBanner(ShopManager.getInstance().getShopMainBanner());
            shopMainView.updateGroup(ShopManager.getInstance().getShopMainGroup());
            shopMainView.clearRecommend();
            shopMainView.updateRecommend(ShopManager.getInstance().getRecommendList());
            shopMainView.updateQgSales(ShopManager.getInstance().getQgSales());
            shopMainView.updateMsSales(ShopManager.getInstance().getMsSales());
            shopMainView.updateCartNum(ShopManager.getInstance().getCartInfo().getCartNum());
            shopMainView.refreshComplete();
            shopMainView.hindLoading();
        }
    }

    @Override
    public void search(final String text)
    {
        shopMainView.showLoading();
        ShopManager.getInstance().getShopListBySearch(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                Gson gson = new Gson();
                try
                {
                    JSONObject data = result.getJSONObject("data");
                    PageInfo pageInfo = gson.fromJson(data.toString(), PageInfo.class);
                    List<SpuInfo> list = gson.fromJson(data.getJSONArray("list").toString(), new TypeToken<List<SpuInfo>>()
                    {
                    }.getType());
                    CategoryShopInfo categoryShopInfo = new CategoryShopInfo();
                    categoryShopInfo.setParam(text);
                    categoryShopInfo.setPageInfo(pageInfo);
                    categoryShopInfo.setList(list);
                    ShopManager.getInstance().setCategoryShopInfo(categoryShopInfo);
                    shopMainView.goShopListActivity(1);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    shopMainView.showMessage(mContext.getString(R.string.json_error));
                }
                shopMainView.hindLoading();
            }

            @Override
            public void failed(String message)
            {
                shopMainView.hindLoading();
                shopMainView.showMessage(mContext.getString(R.string.http_error));
            }
        }, text, 1, "", "desc");
    }

    @Override
    public void refreshRecommend()
    {
        final ShopManager manager = ShopManager.getInstance();
        PageInfo pageInfo = manager.getCurPageInfo();
        if (pageInfo == null || pageInfo.isLastPage())
        {
            shopMainView.showMessage("没有更多推荐了...");
            shopMainView.refreshComplete();
            return;
        }
        shopMainView.showLoading();
        manager.initShopMianRecommend(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                shopMainView.hindLoading();
                Gson gson = new Gson();
                try
                {
                    JSONObject data = result.getJSONObject("data");
                    PageInfo pageInfo = gson.fromJson(data.toString(), PageInfo.class);
                    manager.setCurPageInfo(pageInfo);
                    List<SpuInfo> list = gson.fromJson(data.getJSONArray("list").toString(), new TypeToken<List<SpuInfo>>()
                    {
                    }.getType());
                    manager.setRecommendList(list);
                    shopMainView.updateRecommend(list);
                    shopMainView.refreshComplete();

                } catch (JSONException e)
                {
                    e.printStackTrace();
                    shopMainView.showMessage(mContext.getString(R.string.http_error));
                }
            }

            @Override
            public void failed(String message)
            {
                shopMainView.hindLoading();
                shopMainView.showMessage("加载推荐信息失败...");
                shopMainView.refreshComplete();
            }
        }, pageInfo.getPageNumber() + 1, 10);
    }

    /**
     * 商品分类列表页
     */
    @Override
    public void goShopListByCategory(final String categoryId)
    {
        shopMainView.showLoading();
        ShopManager.getInstance().getShopListByCategoryId(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                Gson gson = new Gson();
                try
                {
                    JSONObject data = result.getJSONObject("data");
                    PageInfo pageInfo = gson.fromJson(data.toString(), PageInfo.class);
                    List<SpuInfo> list = gson.fromJson(data.getJSONArray("list").toString(), new TypeToken<List<SpuInfo>>()
                    {
                    }.getType());
                    CategoryShopInfo categoryShopInfo = new CategoryShopInfo();
                    categoryShopInfo.setParam(categoryId);
                    categoryShopInfo.setPageInfo(pageInfo);
                    categoryShopInfo.setList(list);
                    ShopManager.getInstance().setCategoryShopInfo(categoryShopInfo);
                    shopMainView.goShopListActivity(0);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    shopMainView.showMessage(mContext.getString(R.string.json_error));
                }
                shopMainView.hindLoading();
            }

            @Override
            public void failed(String message)
            {
                shopMainView.hindLoading();
                shopMainView.showMessage(mContext.getString(R.string.http_error));
            }
        }, categoryId, 1, "", "desc");
    }

    @Override
    public void goShopCategoryActivity()
    {
        shopMainView.showLoading();
        CategoryManager.getInstance().getShopCategory(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                shopMainView.hindLoading();
                Gson gson = new Gson();
                try
                {
                    List<CategoryInfo> list = gson.fromJson(result.getJSONArray("data").toString(), new TypeToken<List<CategoryInfo>>()
                    {
                    }.getType());
                    CategoryManager.getInstance().setUiList(list);
                    Intent intent = new Intent(mContext, ShopCategoryActivity.class);
                    mContext.startActivity(intent);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    shopMainView.showMessage(mContext.getString(R.string.json_error));
                }
            }

            @Override
            public void failed(String message)
            {
                shopMainView.hindLoading();
                shopMainView.showMessage(message);
            }
        });
    }

    @Override
    public void goSalesActivity(final int type)
    {
        shopMainView.showLoading();
        ShopSalesManager.getInstance().getSalesListByType(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                shopMainView.hindLoading();
                Gson gson = new Gson();
                try
                {
                    List<SalesListData> list = gson.fromJson(result.getJSONArray("data").toString(), new TypeToken<List<SalesListData>>()
                    {
                    }.getType());
                    ShopSalesManager.getInstance().setmList(list);
                    Intent intent = new Intent(mContext, ShopSalesActivity.class);
                    intent.putExtra("salesType", type);
                    mContext.startActivity(intent);
                } catch (JSONException e)
                {
                    shopMainView.showMessage(mContext.getString(R.string.json_error));
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(String message)
            {
                shopMainView.hindLoading();
                shopMainView.showMessage(message);
            }
        }, type);
    }

}
